﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShopBLL;
using ShopModel;
using ASP;
using System.Text;

public partial class cms_Views : System.Web.UI.Page
{
    #region METHODS

    protected void RefreshNewsList(string SelectValue)
    {
        ddlViews.Items.Clear();

        List<ShopModel.View> NewsList =   ProductsManager.Instance.GetViews(CommonTools.CurrentLanguageID);

        ddlViews.Items.Add(new ListItem(Resources.Language.NewView, ""));
        ddlViews.DataSource = NewsList;
        ddlViews.DataBind();

        ddlViews.SelectedValue = SelectValue;

        if (ddlViews.SelectedValue != string.Empty)
        {
            btnDeleteTop.Enabled = true;
            btnDeleteBottom.Enabled = true;
        }
    }

    protected void ClearData()
    {
        heContent.Text = string.Empty;
        tbTitle.Text = string.Empty;
        btnDeleteTop.Enabled = false;
        btnDeleteBottom.Enabled = false;
    }

    protected void RefreshNewsData()
    {
        ShopModel.View CurrentNews = ProductsManager.Instance.GetViewByID(int.Parse(ddlViews.SelectedValue), int.Parse(ddlLanguage.SelectedValue));

        if (CurrentNews != null)
        {
            heContent.Text = CurrentNews.Template;
            tbTitle.Text = CurrentNews.Title;
            btnDeleteTop.Enabled = true;
            btnDeleteBottom.Enabled = true;
        }
    }

    private void AddScriptsAndAttributes()
    {
        ClientScript.RegisterStartupScript(this.GetType(), "SetTextValue", string.Format("<script type=\"text/javascript\"> hideMarkersText='{0}'; showMarkersText='{1}'; </script>", Resources.Language.TagListHide, Resources.Language.TagList));
        ddlViews.Attributes["onchange"] = "hideHelp();"; 
        ddlLanguage.Attributes["onchange"] = "hideHelp();";
    }

    public void GenerateView(List<Products> productList, ShopModel.View c, Panel pnl)
    {
        pnl.Controls.Clear();
        ShopModel.View v = c;
        StringBuilder sb = new StringBuilder();
        sb.Append(v.Template);

        int j = 0;
        Literal ltrl = new Literal();
        ltrl.ID = "litr" + j++;

        if (v.Template.IndexOf("##ItemTemplate#") != -1 && v.Template.IndexOf("#ItemTemplate##") != -1)
        {
            //wyciecie początkowej części do definicji jednego produktu
            ltrl.Text = v.Template.Substring(0, v.Template.IndexOf("##ItemTemplate#"));
            pnl.Controls.Add(ltrl);
            // lista produktów
            // pobranie definicji wiersza tabeli
            string sItemTemplate = v.Template.Substring(v.Template.IndexOf("##ItemTemplate#") + 15, v.Template.IndexOf("#ItemTemplate##") - (v.Template.IndexOf("##ItemTemplate#") + 15));
            string itemTemplate = string.Empty;
            itemTemplate = sItemTemplate;
            // StringBuilder productsList = new StringBuilder();
            // zamiana znaczników na wartości i dodawanie do productsList
            int i = 1;
            int ilosc = 0;
            foreach (Products product in productList)
            {
                ilosc = 0;
                Literal l1, l2, l3;
                controls_ctrlproductcomparemanager_ascx compare;
                controls_ctrlRates rates;
                ltrl = new Literal();
                ltrl.ID = "ltri" + j++;
                itemTemplate = itemTemplate.Replace("?#PriceNetto?", ( Resources.Language.Currency + " " + product.PriceNetto.ToString("F2")));
                itemTemplate = itemTemplate.Replace("?#PriceBrutto?", (Resources.Language.Currency + " " + product.PriceBrutto.ToString("F2")));
                itemTemplate = itemTemplate.Replace("?#Name?", product.Name);
                itemTemplate = itemTemplate.Replace("?#SpecialPriceBrutto?", (Resources.Language.Currency + " " + product.PriceBrutto.ToString("F2")));
                itemTemplate = itemTemplate.Replace("?#SpecialPriceNetto?", (Resources.Language.Currency + " " + product.PriceNetto.ToString("F2")));
                itemTemplate = itemTemplate.Replace("?#NameUrl?", URLParser.ParseUrl(product.Name));
                itemTemplate = itemTemplate.Replace("?#ProductID?", product.IDproduct.ToString());
                itemTemplate = itemTemplate.Replace("?#AddToBasket?", @"<a href='#' onclick='addToBasket(" + product.IDproduct + ");return false'>" + Resources.Language.AddToBasket + "</a>");
                itemTemplate = itemTemplate.Replace("?#ShortDescription?", product.ShortDescription);
                itemTemplate = itemTemplate.Replace("?#PromotedText?", Resources.Language.Promoted);
                itemTemplate = itemTemplate.Replace("?#Product?", Resources.Language.Product);

                if (product.Pictures.Count > 0)
                {
                    itemTemplate = itemTemplate.Replace("?#ThumbSrc?", product.Pictures[0].Miniature.VirtualPath.Replace("~", ""));
                }

                if (sItemTemplate.IndexOf("?#AddToCompare?") >= 0) ilosc++;
                if (sItemTemplate.IndexOf("?#Rates?") >= 0) ilosc++;

                if (ilosc == 0)
                {
                    ltrl.Text = itemTemplate;
                    pnl.Controls.Add(ltrl);
                }
                else if (ilosc == 1 && sItemTemplate.IndexOf("?#AddToCompare?") >= 0)
                {
                    l1 = new Literal();
                    l2 = new Literal();
                    l1.ID = "ltrr" + j++;
                    l2.ID = "ltrn" + j++;
                    compare = LoadControl("../controls/ctrlProductCompareManager.ascx") as controls_ctrlproductcomparemanager_ascx;//new controls_ctrlproductcomparemanager_ascx();
                    compare.ID = "cmp" + j++;
                    compare.ProductID = product.IDproduct;
                    //compare.SelectedProductsChanged += new EventHandler(pcmSelectedProducts_Changed);
                    l1.Text = itemTemplate.Substring(0, itemTemplate.IndexOf("?#AddToCompare?"));
                    l2.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#AddToCompare?") + 15);
                    pnl.Controls.Add(l1);
                    pnl.Controls.Add(compare);
                    pnl.Controls.Add(l2);

                }
                else if (ilosc == 1 && sItemTemplate.IndexOf("?#Rates?") >= 0)
                {
                    l1 = new Literal();
                    l2 = new Literal();
                    l1.ID = "ltro" + j++;
                    l2.ID = "ltrz" + j++;
                    rates = LoadControl("../controls/ctrlRates.ascx") as controls_ctrlRates;//new controls_ctrlRates();
                    rates.ID = "rat" + j++;
                    rates.ProductID = product.IDproduct.ToString();
                    l1.Text = itemTemplate.Substring(0, itemTemplate.IndexOf("?#Rates?"));
                    l2.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#Rates?") + 8);
                    pnl.Controls.Add(l1);
                    pnl.Controls.Add(rates);
                    pnl.Controls.Add(l2);
                }
                else if (ilosc == 2)
                {
                    l1 = new Literal();
                    l2 = new Literal();
                    l3 = new Literal();
                    l1.ID = "ltrp" + j++;
                    l2.ID = "ltry" + j++;
                    l3.ID = "ltrw" + j++;
                    compare = LoadControl("../controls/ctrlProductCompareManager.ascx") as controls_ctrlproductcomparemanager_ascx;//new controls_ctrlproductcomparemanager_ascx();
                    compare.ID = "cmp" + j++;
                    compare.ProductID = product.IDproduct;
                    //compare.SelectedProductsChanged += new EventHandler(pcmSelectedProducts_Changed);
                    rates = LoadControl("../controls/ctrlRates.ascx") as controls_ctrlRates;//new controls_ctrlRates();
                    rates.ID = "rat" + j++;
                    rates.ProductID = product.IDproduct.ToString();
                    if (sItemTemplate.IndexOf("?#Rates?") < sItemTemplate.IndexOf("?#AddToCompare?"))
                    {
                        l1.Text = itemTemplate.Substring(0, itemTemplate.IndexOf("?#Rates?"));
                        l2.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#Rates?") + 8, (itemTemplate.IndexOf("?#AddToCompare?") - (itemTemplate.IndexOf("?#Rates?") + 8)));
                        l3.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#AddToCompare?") + 15);

                        pnl.Controls.Add(l1);
                        pnl.Controls.Add(rates);
                        pnl.Controls.Add(l2);
                        pnl.Controls.Add(compare);
                        pnl.Controls.Add(l3);
                    }
                    else
                    {
                        l1.Text = itemTemplate.Substring(0, itemTemplate.IndexOf("?#AddToCompare?"));
                        l2.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#AddToCompare?") + 15, (itemTemplate.IndexOf("?#Rates?") - (itemTemplate.IndexOf("?#AddToCompare?") + 15)));
                        l3.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#Rates?") + 8);

                        pnl.Controls.Add(l1);
                        pnl.Controls.Add(compare);
                        pnl.Controls.Add(l2);
                        pnl.Controls.Add(rates);
                        pnl.Controls.Add(l3);
                    }
                }

                //itemTemplate.Replace("?#AddToCompare?", "");
                //itemTemplate.Replace("?#Rates?", "");
                //productsList.Append(itemTemplate.ToString());
                //itemTemplate = string.Empty;
                itemTemplate = sItemTemplate;
                i++;
            }

            //sb.Replace(sItemTemplate, productsList.ToString());
            //sb.Replace("##ItemTemplate#", string.Empty);
            // sb.Replace("#ItemTemplate##", string.Empty);


            //wycięcie końcowej części po definicji produktu
            ltrl = new Literal();
            ltrl.ID = "lthr1" + j++;
            ltrl.Text = v.Template.Substring(v.Template.IndexOf("#ItemTemplate##") + 15);
            pnl.Controls.Add(ltrl);
        }
        else
        {
            ltrl.Text = sb.ToString();
            pnl.Controls.Add(ltrl);
        }
        pnl.Visible = true;
        // lView.Text = sb.ToString();
    }

    #endregion METHODS

    #region EVENTS

    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlViews.SelectedValue != string.Empty)
            RefreshNewsData();
        else
            ClearData();
    }

    protected void ddlNews_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlViews.SelectedValue != string.Empty)
            RefreshNewsData();
        else
            ClearData();
    }

    protected void New_Click(object sender, EventArgs e)
    {
        ClearData();
        ddlViews.SelectedIndex = 0;
    }

    protected void Save_Click(object sender, EventArgs e)
    {
        ShopModel.View news = new ShopModel.View(tbTitle.Text,  heContent.Text);

        if (ddlViews.SelectedValue != string.Empty)
            news.ViewID = int.Parse(ddlViews.SelectedValue);

        int id = ProductsManager.Instance.SaveView(news, int.Parse(ddlLanguage.SelectedValue));

        if (id > 0)
            CtrlShowInfo.ShowInfo(false, Resources.Language.cmsMessageDataSaveSuccessful);
        else
            CtrlShowInfo.ShowInfo(true, Resources.Language.cmsMessageDataSaveFailure);

        RefreshNewsList(id.ToString());
    }

    protected void Delete_Click(object sender, EventArgs e)
    {
        if (ProductsManager.Instance.DeleteView(int.Parse(ddlViews.SelectedValue)))
        {
            CtrlShowInfo.ShowInfo(false, Resources.Language.NewsDeleted);
        }
        else
        {
            CtrlShowInfo.ShowInfo(true, Resources.Language.Error_WhileDeleting);
        }
        RefreshNewsList(string.Empty);
        ClearData();
    }

    protected void btnTestNotification_Click(object sender, EventArgs e)
    {
        if (btnTestNotificationTop.Text == Resources.Language.TestView)
        {
            btnTestNotificationTop.Text = Resources.Language.HideView;
            btnTestNotificationBottom.Text = Resources.Language.HideView;

            ShopModel.View v = new ShopModel.View();
            v.Template = heContent.Text;
            ProductSearchCriteria args = new ProductSearchCriteria();
            args.ProducerId = -1;
            args.CategoryId = -1;
            int pCount = 0;
            int page = 1;
            GenerateView(ProductsManager.Instance.SearchProduct(args, SortMethod.NameAscending, ref page, 5, out pCount, true, CommonTools.CurrentLanguageID), v, pnlView);
        
        }
        else
        {
            btnTestNotificationTop.Text = Resources.Language.TestView;
            btnTestNotificationBottom.Text = Resources.Language.TestView;
            pnlView.Controls.Clear();
            pnlView.Visible = false;
        }
    }

    #endregion EVENTS

    #region PAGE EVENTS

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            RefreshNewsList(string.Empty);

            List<Language> AvailableLanguages = ReportsManager.Instance.GetAvailableLanguages(true);
            ddlLanguage.DataSource = AvailableLanguages;
            ddlLanguage.DataBind();

            ddlLanguage.SelectedValue = CommonTools.CurrentLanguageID.ToString();
        }
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        AddScriptsAndAttributes();
    }

    #endregion PAGE EVENTS

}
